import wepy from 'wepy';
import tip from './tip'
import {getSystemInfo,getSignature,getReqRaw,getTimestampOfSecends,getWxLoginCode,getSess,throttle,checkSession} from './utils';
// const base_url = 'https://apitest.crotnet.com/miniprogram/v1'  //测试地址
const base_url = 'https://api.1hocang.com/miniprogram/v1'


/* 公共的请求方法 */
const wxRequest = async(action,params,USEAES=false) => {

    throttle(()=>{tip.loading();},1000);

    let reqRaw = params?getReqRaw(params,USEAES):'';
    let timestamp = getTimestampOfSecends();
    let session_id = getSess('session_id',action);
    let key = getSess('key',action);
    let signature = getSignature(action,session_id,reqRaw,timestamp,key);
    let data = {
        action,session_id, reqRaw,timestamp, signature 
    }
    
    let res = await wepy.request({
        url: base_url,
        json: true,
        method: 'POST',
        data,
    });
    console.log('action>>>>>>>>',action,'>>>>>>>>',params,'>>>>>>>>>>',res)
    tip.loaded();
    if(res.statusCode!=200 && res.statusCode!=304 && res.statusCode!=400){
        res = {data:{code:-1,msg:res.statusCode+''}};
    }
    if(res.data.code==104||res.data.code==105){
        wepy.clearStorageSync();
        res = {data:{code:-1,msg:res.data.msg+',请刷新或删除重试'}};
    } 
    return res;
};


/* 小程序初始化 */
const initData = async() => {
    const isResetInit = await checkSession();
    if(isResetInit){
        const {platform,screenWidth,screenHeight,version} = getSystemInfo();
        const scene = wepy.getStorageSync('scene');
        let params = {
            channel: scene?scene:'wx_mn_official',
            app_version: version,
            device_type: platform=='android'?1:2,
            app_type: 4,
            device_size:screenWidth + ',' + screenHeight,
            code:await getWxLoginCode()
        };
        
        const res = await wxRequest(1006,params);
        console.log('小程序初始化',params,res)
        if (res.data.code == 0) {
            const data = res.data.data;
            data.initTime = new Date();
            wepy.setStorageSync('initData', data);
            return data;
        } else {
            return res.data.msg;
        } 
    }else{
        return '不需要重新初始化';
    }
}



module.exports = {
    wxRequest,initData
}
